package cc.comac.mom.datahandlers.entity;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cc.comac.mom.bean.ImportReultData;
import cc.comac.mom.bean.QualityAsrFeatures;
import cc.comac.mom.bean.QualityAsrFeaturesBean;
import cc.comac.mom.config.OSSService;
import cc.comac.mom.dao.entity.QualityAsrFeaturesDao;
import cc.comac.mom.entity.QualityAsrFeaturesEntity;
import cc.comac.mom.util.BaseEntityDataUtil;
import cc.comac.mom.util.ExcelUploadUtil;
import cc.comac.mom.util.ExportExcel;
import cc.comac.mom.util.GetGeneralFieldValue;
import cc.comac.mom.util.ResultBean;

@Component
@Transactional
public class QualityAsrFeaturesDataHandler extends ServiceImpl<QualityAsrFeaturesDao, QualityAsrFeaturesEntity> {
	@Autowired
	private QualityAsrFeaturesDao QualityAsrFeaturesDao;
	@Autowired
	private BaseEntityDataUtil baseEntityDataUtil;
	@Autowired
	private QualityAsrCheckFormDetailDataHandler qualityAsrCheckFormDetailDataHandler;

	@Autowired
	private QualityAsrCheckFormDataHandler qualityAsrCheckFormDataHandler;

	@Autowired
	private OSSService oSService;
	/**
	 * 批量导入
	 * 
	 * @param QualityAsrFeaturesList
	 * @return
	 */
	public int insertBatch(List<QualityAsrFeatures> QualityAsrFeaturesList) {
		// 保存数据
		if (QualityAsrFeaturesList == null || QualityAsrFeaturesList.size() < 1) {
			throw new RuntimeException("未检测到数据！");
		}
		for (QualityAsrFeatures QualityAsrFeatures : QualityAsrFeaturesList) {
			baseEntityDataUtil.setBaseEntityData(QualityAsrFeatures);
		}
		Integer insert = QualityAsrFeaturesDao.insertAsrFeaturesBatch(QualityAsrFeaturesList);
		return insert;
	}

	/**
	 * 分页查询
	 * 
	 * @param equipParamItem
	 * @return
	 */
	public QualityAsrFeatures selectAllByPage(QualityAsrFeatures QualityAsrFeatures) {
		QualityAsrFeatures returnQualityAsrFeatures = new QualityAsrFeatures();
		if (QualityAsrFeatures.getPageNum() == 0) {
			QualityAsrFeatures.setPageNum(1);
		}
		if (QualityAsrFeatures.getPageSize() == 0) {
			QualityAsrFeatures.setPageSize(10);
		}

		QueryWrapper<QualityAsrFeaturesEntity> queryWrapper = new QueryWrapper<QualityAsrFeaturesEntity>();
		queryWrapper.eq("row_status", 1);
		if (QualityAsrFeatures.getPartNumber() != null && !"".equals(QualityAsrFeatures.getPartNumber())) {
			queryWrapper.like("part_number", QualityAsrFeatures.getPartNumber());
		}
		if (QualityAsrFeatures.getFeatures() != null && !"".equals(QualityAsrFeatures.getFeatures())) {
			queryWrapper.like("features", QualityAsrFeatures.getFeatures());
		}
		if (QualityAsrFeatures.getSize() != null && !"".equals(QualityAsrFeatures.getSize())) {
			queryWrapper.like("size", QualityAsrFeatures.getSize());
		}
		if (QualityAsrFeatures.getInitialReliabilityValue() != null
				&& !"".equals(QualityAsrFeatures.getInitialReliabilityValue())) {
			queryWrapper.like("initial_reliability_value", QualityAsrFeatures.getInitialReliabilityValue());
		}
		if (QualityAsrFeatures.getGrade() != null && !"".equals(QualityAsrFeatures.getGrade())) {
			queryWrapper.like("grade", QualityAsrFeatures.getGrade());
		}
		// 不返回总记录数 设置false
		Page<QualityAsrFeaturesEntity> page = new Page<>(QualityAsrFeatures.getPageNum(),
				QualityAsrFeatures.getPageSize(), true);
		IPage<QualityAsrFeaturesEntity> iPage = QualityAsrFeaturesDao.selectPage(page, queryWrapper);
		List<QualityAsrFeaturesEntity> records = iPage.getRecords();
		returnQualityAsrFeatures.setPageNum(QualityAsrFeatures.getPageNum());
		returnQualityAsrFeatures.setPageSize(QualityAsrFeatures.getPageSize());
		returnQualityAsrFeatures.setEntityList(records);
		returnQualityAsrFeatures.setTotalQuantity((int) iPage.getTotal());
		returnQualityAsrFeatures.setPageCount((int) iPage.getPages());
		return returnQualityAsrFeatures;
	}

	public List<QualityAsrFeaturesEntity> selectAll(QualityAsrFeatures QualityAsrFeatures) {
		QueryWrapper<QualityAsrFeaturesEntity> queryWrapper = new QueryWrapper<QualityAsrFeaturesEntity>();
		queryWrapper.eq("row_status", 1);
		if (QualityAsrFeatures.getPartNumber() != null && !"".equals(QualityAsrFeatures.getPartNumber())) {
			queryWrapper.like("part_number", QualityAsrFeatures.getPartNumber());
		}
		if (QualityAsrFeatures.getFeatures() != null && !"".equals(QualityAsrFeatures.getFeatures())) {
			queryWrapper.like("features", QualityAsrFeatures.getFeatures());
		}
		if (QualityAsrFeatures.getSize() != null && !"".equals(QualityAsrFeatures.getSize())) {
			queryWrapper.like("size", QualityAsrFeatures.getSize());
		}
		if (QualityAsrFeatures.getInitialReliabilityValue() != null
				&& !"".equals(QualityAsrFeatures.getInitialReliabilityValue())) {
			queryWrapper.like("initial_reliability_value", QualityAsrFeatures.getInitialReliabilityValue());
		}
		if (QualityAsrFeatures.getGrade() != null && !"".equals(QualityAsrFeatures.getGrade())) {
			queryWrapper.like("grade", QualityAsrFeatures.getGrade());
		}
		List<QualityAsrFeaturesEntity> selectList = QualityAsrFeaturesDao.selectList(queryWrapper);
		return selectList;
	}

	/**
	 * 添加ASR特征库
	 * 
	 * @param QualityAsrFeatures
	 * @return
	 */
	public int insert(QualityAsrFeatures QualityAsrFeatures) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 校验参数组编码是否重复
		map.put("row_status", 1);
		map.put("part_number", QualityAsrFeatures.getPartNumber());
		map.put("features", QualityAsrFeatures.getFeatures());
		map.put("size", QualityAsrFeatures.getSize());
		map.put("initial_reliability_value", QualityAsrFeatures.getInitialReliabilityValue());
		map.put("grade", QualityAsrFeatures.getGrade());
		map.put("features_count", QualityAsrFeatures.getFeaturesCount());
		List<QualityAsrFeaturesEntity> selectInfo = QualityAsrFeaturesDao.selectByMap(map);
		if (selectInfo != null && selectInfo.size() > 0) {
			throw new RuntimeException("添加失败，已存在相同数据！");
		}
		baseEntityDataUtil.setBaseEntityData(QualityAsrFeatures);
		Integer insert = QualityAsrFeaturesDao.insert((QualityAsrFeaturesEntity) QualityAsrFeatures);
		return insert;
	}

	/**
	 * 修改ASR特征库
	 * 
	 * @param QualityAsrFeatures
	 * @return
	 */
	public int update(QualityAsrFeatures QualityAsrFeatures) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 校验参数组编码是否重复
		map.put("row_status", 1);
		map.put("part_number", QualityAsrFeatures.getPartNumber());
		map.put("features", QualityAsrFeatures.getFeatures());
		map.put("size", QualityAsrFeatures.getSize());
		map.put("initial_reliability_value", QualityAsrFeatures.getInitialReliabilityValue());
		map.put("grade", QualityAsrFeatures.getGrade());
		map.put("features_count", QualityAsrFeatures.getFeaturesCount());
		List<QualityAsrFeaturesEntity> selectInfo = QualityAsrFeaturesDao.selectByMap(map);
		if (selectInfo != null && selectInfo.size() > 0 && QualityAsrFeatures.getId() != selectInfo.get(0).getId()) {
			throw new RuntimeException("修改失败，已存在相同数据！");
		}
		QualityAsrFeatures.setLastModifiedTime(LocalDateTime.now());
		QualityAsrFeatures.setLastModifier(GetGeneralFieldValue.getCurrentUser());
		Integer insert = QualityAsrFeaturesDao.updateById((QualityAsrFeaturesEntity) QualityAsrFeatures);
		return insert;
	}

	/**
	 * 批量删除ASR特征库
	 * 
	 * @param QualityAsrFeaturesList
	 * @return
	 */
	public int batchDelete(List<QualityAsrFeatures> QualityAsrFeaturesList) {
		List<QualityAsrFeaturesEntity> list = new ArrayList<QualityAsrFeaturesEntity>();
		// 预留删除校验
		for (QualityAsrFeatures QualityAsrFeatures : QualityAsrFeaturesList) {
			QualityAsrFeaturesEntity QualityAsrFeaturesEntity = new QualityAsrFeaturesEntity();
			QualityAsrFeaturesEntity.setId(QualityAsrFeatures.getId());
			QualityAsrFeaturesEntity.setRowStatus(0);
			QualityAsrFeaturesEntity.setLastModifiedTime(GetGeneralFieldValue.getLocalDateTime());
			QualityAsrFeaturesEntity.setLastModifier(GetGeneralFieldValue.getCurrentUser());
			list.add(QualityAsrFeaturesEntity);
		}
		// 批量更新数据
		boolean updateBatchById = updateBatchById(list);
		return updateBatchById ? 1 : 0;
	}

	/**
	 * 批量更新
	 * 
	 * @param entityList
	 * @return
	 */
	@Override
	public boolean updateBatchById(Collection<QualityAsrFeaturesEntity> entityList) {
		return super.updateBatchById(entityList);
	}

	/**
	 * 通过特征库主键id的集合查询对应数据
	 * 
	 * @param entityList
	 * @return
	 */
	public List<QualityAsrFeaturesBean> selectByIds(List<Long> ids) {
		QueryWrapper<QualityAsrFeaturesEntity> queryWrapper = new QueryWrapper<QualityAsrFeaturesEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.in("asr_features_id", ids);
		List<QualityAsrFeaturesEntity> selectList = QualityAsrFeaturesDao.selectList(queryWrapper);
		List<QualityAsrFeaturesBean> beanList = new ArrayList<QualityAsrFeaturesBean>();
		for (QualityAsrFeaturesEntity qualityAsrFeaturesEntity : selectList) {
			QualityAsrFeaturesBean qualityAsrFeaturesBean = new QualityAsrFeaturesBean();
			qualityAsrFeaturesBean.setInnerData(qualityAsrFeaturesEntity);
			beanList.add(qualityAsrFeaturesBean);
		}
		return beanList;
	}

	// 通过材料零件图号查询对应数据
	public List<QualityAsrFeaturesBean> selectByPartNumber(String partNumber) {
		QueryWrapper<QualityAsrFeaturesEntity> queryWrapper = new QueryWrapper<QualityAsrFeaturesEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("part_number", partNumber);
		List<QualityAsrFeaturesEntity> selectList = QualityAsrFeaturesDao.selectList(queryWrapper);

		List<QualityAsrFeaturesBean> beanList = new ArrayList<QualityAsrFeaturesBean>();
		if (selectList.size() > 0) {
			for (QualityAsrFeaturesEntity qualityAsrFeaturesEntity : selectList) {
				QualityAsrFeaturesBean qualityAsrFeaturesBean = new QualityAsrFeaturesBean();
				qualityAsrFeaturesBean.setInnerData(qualityAsrFeaturesEntity);
				beanList.add(qualityAsrFeaturesBean);
			}
		}
		return beanList;
	}

	public String exportData(HttpServletRequest request, HttpServletResponse response, QualityAsrFeatures obj) {
		List<QualityAsrFeaturesEntity> entityList = selectAll(obj);
		
		// excel中对应的表头
		String[] rowName = new String[] { "材料/零件图号", "特征", "尺寸", "初始可靠值", "等级", "特征计数" };
		List<Object[]> dataList = new ArrayList<Object[]>();
		for (QualityAsrFeaturesEntity qualityAsrFeaturesEntity : entityList) {
			Object[] objs = new Object[rowName.length];
			objs[0] = qualityAsrFeaturesEntity.getPartNumber();
			objs[1] = qualityAsrFeaturesEntity.getFeatures();
			objs[2] = qualityAsrFeaturesEntity.getSize();
			objs[3] = qualityAsrFeaturesEntity.getInitialReliabilityValue();
			objs[4] = qualityAsrFeaturesEntity.getGrade();
			objs[5] = qualityAsrFeaturesEntity.getFeaturesCount();
			dataList.add(objs);
		}
//		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		String fileName = "ASR特征库数据";
		// 执行导出
		HSSFWorkbook exportExcel = ExportExcel.exportExcel(request, response, fileName, rowName, dataList,
				"yyyy-MM-dd HH:mm:ss");
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			exportExcel.write(baos);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
		String updateSheet = oSService.updateSheet(swapStream, fileName);
		return updateSheet;
	}

	public ResultBean importEquipDevType(MultipartFile file, String rootPath) {
		ResultBean resultBean = new ResultBean(true);
//		File chunkFile = ExcelUploadUtil.validateImportDate(file, rootPath);
		// 已存在设备编号
		ArrayList<QualityAsrFeaturesEntity> listPartNumber = new ArrayList<QualityAsrFeaturesEntity>();
		// 新增的数据集合
		ArrayList<QualityAsrFeaturesEntity> listEntity = new ArrayList<QualityAsrFeaturesEntity>();
		// 失败的数据集合
		ArrayList<Object> errorList = new ArrayList<Object>();
		
		// 查询数据库存在的设备编号，添加到已存在的数据集合里
		QueryWrapper<QualityAsrFeaturesEntity> queryWrapper = new QueryWrapper<QualityAsrFeaturesEntity>();
		queryWrapper.eq("row_status", 1);
		List<QualityAsrFeaturesEntity> asrFeaturesEntityList = QualityAsrFeaturesDao.selectList(queryWrapper);
		if (asrFeaturesEntityList != null && asrFeaturesEntityList.size() > 0) {
			for (QualityAsrFeaturesEntity item : asrFeaturesEntityList) {
				listPartNumber.add(item);
			}
		}
		try {
			// FileInputStream in = new FileInputStream(file);
//			FileInputStream in = new FileInputStream(chunkFile);
//			Workbook workbook;
//			workbook = ExcelUploadUtil.getWorkbok(in, chunkFile);
			Workbook workbook = ExcelUploadUtil.getWorkBook(file);
			// Sheet的数量
			int sheetCount = workbook.getNumberOfSheets();
			// 循环sheet
			for (int i = 0; i < sheetCount; i++) {
				Sheet sheetAt = workbook.getSheetAt(i);
				// 行数
				int rowCount = sheetAt.getLastRowNum();
				System.out.println(rowCount + "行数");
				// 跳过第一行
				if (rowCount < 1) {
					continue;
				}
				// 循环行
				for (int j = 1; j <= rowCount; j++) {
					Row row = sheetAt.getRow(j);
					int cellCount = row.getPhysicalNumberOfCells();
					System.out.println(cellCount + "列数");
					Cell cell0 = row.getCell(0);
					Object partNumber = ExcelUploadUtil.getValue(cell0);
					QualityAsrFeaturesEntity asrFeayuresEntity = new QualityAsrFeaturesEntity();
					for (QualityAsrFeaturesEntity qualityAsrFeaturesEntity : asrFeaturesEntityList) {
						if (qualityAsrFeaturesEntity.getPartNumber().equals(partNumber) || StringUtils.isEmpty(qualityAsrFeaturesEntity.getPartNumber())) {
							ArrayList<Object> arrayList = new ArrayList<Object>();
							for (Cell cell : row) {
								arrayList.add(ExcelUploadUtil.getValue(cell));
							}
							errorList.add(arrayList);
							continue;
						}
					}
					// 数据为空
					if (partNumber == null) {
						continue;
					}
					asrFeayuresEntity.setPartNumber(partNumber.toString());
					Object features = ExcelUploadUtil.getValue(row.getCell(1));
					if (features != null && features instanceof String) {
						asrFeayuresEntity.setFeatures((String) features);
					}

					Object size = ExcelUploadUtil.getValue(row.getCell(2));
					if (size != null && size instanceof String) {
						asrFeayuresEntity.setSize((String) size);
					}
					Object initialReliabilityValue = ExcelUploadUtil.getValue(row.getCell(3));
					if (initialReliabilityValue != null && initialReliabilityValue instanceof String) {
						asrFeayuresEntity.setInitialReliabilityValue((String) initialReliabilityValue);
					}
					Object grade = ExcelUploadUtil.getValue(row.getCell(4));
					if (grade != null && grade instanceof String) {
						asrFeayuresEntity.setGrade((String) grade);
					}
					Object featuresCount = ExcelUploadUtil.getValue(row.getCell(5));
					if (featuresCount != null && featuresCount instanceof String) {
						asrFeayuresEntity.setFeaturesCount((String) grade);
					}
					// 数据已存在
					if (listPartNumber.contains(asrFeayuresEntity)) {
						// 设备编号已经存在
						continue;
					}
					listEntity.add(asrFeayuresEntity);
					listPartNumber.add(asrFeayuresEntity);

				}

			}
//			chunkFile.delete();
			for (QualityAsrFeaturesEntity qualityAsrFeaturesEntity : listEntity) {
				baseEntityDataUtil.setBaseEntityData(qualityAsrFeaturesEntity);
			}
			this.saveBatch(listEntity, listEntity.size());
		} catch (Exception e) {
			e.printStackTrace();
		}
//		chunkFile.delete();
		ImportReultData importReultData = new ImportReultData();
		int successCount = listEntity.size();
		int errorCount = errorList.size();
		importReultData.setErrorList(errorList);
		importReultData.setErrorRow(errorCount);
		importReultData.setSuccessRow(successCount);
		importReultData.setTotalRow(errorCount+successCount);
		resultBean.setObject(importReultData);
		return resultBean;
	}
}
